// loginRefresh

import { loginRefresh } from "@/services/login";

export default {
  async install(app) {
    // console.log("user___", JSON.parse(uni.getStorageSync("user")).permissions);
    app.directive("focus", {
      // 当被绑定的元素挂载到 DOM 中时...
      mounted(el) {
        // 聚焦元素
        el.focus();
      },
    });
    app.directive("permission", async (el, binding) => {
      const { value } = binding;
      if (!uni.getStorageSync("loginRefresh")) {
        if (uni.getStorageSync("X-Auth-Token")) {
          uni.setStorageSync("loginRefresh", 1);
          const res = await loginRefresh();
          if (res.code == 200) {
            uni.setStorageSync("X-Auth-Token", res.data.token);
            uni.setStorageSync("user", JSON.stringify(res.data.user));
            if (res.data.user.permissions[0].indexOf("manager:") !== -1) {
              uni.setStorageSync("shopType", 2);
              uni.setStorageSync("selectShopType", "admin");
            } else {
              uni.setStorageSync("shopType", 1);
              uni.setStorageSync("selectShopType", "shop");
            }

            // if (res.data.user.adminPermission) {
            //   uni.setStorageSync(
            //     "shopType",
            //     res.data.user.adminPermission ? 2 : 1
            //   );
            //   uni.setStorageSync(
            //     "selectShopType",
            //     res.data.user.adminPermission ? "admin" : "shop"
            //   );
            // } else {
            //   uni.setStorageSync(
            //     "shopType",
            //     res.data.user.adminPermission ? 2 : 1
            //   );
            //   uni.setStorageSync(
            //     "selectShopType",
            //     res.data.user.adminPermission ? "admin" : "shop"
            //   );
            // }
          }
        }
      }

      //const userRoles = getCurrentUserRoles() // 获取当前用户角色的方法
      const userRoles = uni.getStorageSync("user")
        ? JSON.parse(uni.getStorageSync("user")).permissions
        : ["sdasassads", "1231232"]; //模拟数据
      if (value && value instanceof Array && value.length > 0) {
        const hasPermission = userRoles.some((role) => {
          return value.includes(role);
        });

        if (!hasPermission) {
          el.parentNode && el.parentNode.removeChild(el);
        }
      } else {
        throw new Error(`需要指定权限，例如 v-permission="['admin','editor']"`);
      }
    });
  },
};
